package com.acme.bankapp.service.bank;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;
import java.util.Scanner;

import com.acme.BankApplication;
import com.acme.bankapp.domain.bank.Account;
import com.acme.bankapp.domain.bank.CheckingAccount;
import com.acme.bankapp.domain.bank.Client;
import com.acme.bankapp.domain.bank.Gender;
import com.acme.bankapp.domain.bank.SavingsAccount;

public class BankDataLoaderServise {
	private static String account;
	private static double balance;
	private static double overdraft;
	private static String name;
	private static String gender;

	public static void parseFeed(File file) throws IOException,
			ClientExistsException, AccountDoesntExistsException {
		FileReader fileReader = new FileReader(file);
		LineNumberReader lineNumberReader = new LineNumberReader(fileReader);
		String s;
		int index;
		String value;
		String param;
		String delim = ";";
		while ((s = lineNumberReader.readLine()) != null) {
			Scanner scanner = new Scanner(s);
			scanner.useDelimiter(delim);
			while (scanner.hasNext()) {
				s = scanner.next();
				index = s.lastIndexOf("=");
				value = s.substring(index + 1);
				param = s.substring(0, index);
				switch (param) {
				case "accounttype":
					account = value;
					break;
				case "balance":
					balance = Double.parseDouble(value);
					break;
				case "overdraft":
					overdraft = Double.parseDouble(value);
					break;
				case "name":
					name = value;
					break;
				case "gender":
					gender = value;
					break;
				}
			}
			loadFeed();
			scanner.close();
		}
		lineNumberReader.close();
	}

	private static void loadFeed() throws ClientExistsException, AccountDoesntExistsException, IOException {
		if (gender.equals("m")) {
			Client client = BankService.addClient(BankApplication.bank1, name,
					Gender.MALE);
			if (account.equals("c")) {
				Account account = new CheckingAccount(0, balance, overdraft);
				client.addAccount(account);
			} else {
				Account account = new SavingsAccount(0, balance);
				client.addAccount(account);
			}
		} else {
			Client client = BankService.addClient(BankApplication.bank1, name,
					Gender.FEMALE);
			if (account.equals("c")) {
				Account account = new CheckingAccount(0, balance, overdraft);
				client.addAccount(account);
			} else {
				Account account = new SavingsAccount(0, balance);
				client.addAccount(account);
			}
		}
	}

}